package com.company.card_service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.company.card_service.config.loginInterceptConfig.JwtHelper;
import com.company.card_service.mapper.EmployeeMapper;
import com.company.card_service.mapper.EmployeeViewMapper;
import com.company.card_service.mapper.UserLoginLogMapper;
import com.company.card_service.model.Employee;
import com.company.card_service.model.EmployeeView;
import com.company.card_service.model.UserInfo;
import com.company.card_service.mapper.UserInfoMapper;
import com.company.card_service.model.UserLoginLog;
import com.company.card_service.service.UserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.card_service.util.IpUtil;
import com.company.card_service.util.PageHelper;
import com.company.card_service.vo.EvEdApFvVo;
import com.company.card_service.vo.Result;
import com.company.card_service.vo.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 赵志浩
 * @since 2022-09-15 04:15:07
 */
@Service
@Slf4j
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private EmployeeViewMapper employeeViewMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private UserLoginLogMapper userLoginLogMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public Map AuthLogin(long employeeId,HttpServletRequest request, UserInfo userInfo) {
        Map res = new HashMap();
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserInfo::getOpenId,userInfo.getOpenId());
        UserInfo userInfo1 = this.baseMapper.selectOne(lambdaQueryWrapper);
        UserLoginLog userLoginLog = new UserLoginLog();
        if(userInfo1 != null){
            String token = JwtHelper.createToken(Long.valueOf(userInfo1.getId()),
                    userInfo.getWxName());
            LambdaQueryWrapper<Employee> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper2.eq(Employee::getPhone,userInfo1.getPhone());
            Employee employee = employeeMapper.selectOne(lambdaQueryWrapper2);
            addUserLog(request,userInfo1);
            if(employee != null){
                res.put("employeeId",employee.getId());
            }
            else {
                addEmployeeView(employeeId,userInfo1);
            }
            res.put("UserData",userInfo1);
            res.put("token",token);

        }else{
            userInfo.setCreateTime(new Date());
            this.baseMapper.insert(userInfo);
            UserInfo userInfo2 = this.baseMapper.selectOne(lambdaQueryWrapper);
            if(userInfo2 != null){
                String token = JwtHelper.createToken(Long.valueOf(userInfo2.getId()),
                        userInfo2.getWxName());
                addUserLog(request,userInfo2);
                LambdaQueryWrapper<Employee> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper2.eq(Employee::getPhone,userInfo2.getPhone());
                Employee employee = employeeMapper.selectOne(lambdaQueryWrapper2);
                if(employee != null){
                    res.put("employeeId",employee.getId());
                }
                else {
                    addEmployeeView(employeeId,userInfo2);
                }
                addEmployeeView(employeeId,userInfo2);
                res.put("UserData",userInfo2);
                res.put("token",token);
            }

        }
        return res;
    }


    public void addUserLog(HttpServletRequest request,UserInfo userInfo){
        UserLoginLog userLoginLog = new UserLoginLog();
        String ipAddress = IpUtil.getIpAddress(request);
        userLoginLog.setUserId(Long.valueOf(userInfo.getId()));
        userLoginLog.setCity(userInfo.getProvince());
        userLoginLog.setIp(ipAddress);
        userLoginLog.setCreateTime(new Date());
        userLoginLogMapper.insert(userLoginLog);
    }

    public void addEmployeeView(long employeeId,UserInfo userInfo){
        EmployeeView employeeView = new EmployeeView();
        employeeView.setEmployeeId(Integer.valueOf((int) employeeId));
        employeeView.setUserId(userInfo.getId());
        employeeView.setCreateTime(new Date());
        employeeViewMapper.insert(employeeView);

    }

    public Map AuthLogin(HttpServletRequest request, UserInfo userInfo){
        Map res = new HashMap();
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserInfo::getOpenId,userInfo.getOpenId());
        UserInfo userInfo1 = this.baseMapper.selectOne(lambdaQueryWrapper);
        UserLoginLog userLoginLog = new UserLoginLog();
        if(userInfo1 != null){
            String token = JwtHelper.createToken(Long.valueOf(userInfo1.getId()),
                    userInfo.getWxName());
            LambdaQueryWrapper<Employee> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper2.eq(Employee::getPhone,userInfo1.getPhone());
            Employee employee = employeeMapper.selectOne(lambdaQueryWrapper2);
            addUserLog(request,userInfo1);
            if(employee != null){
                res.put("employeeId",employee.getId());
            }
            res.put("UserData",userInfo1);
            res.put("token",token);

        }else{
            userInfo.setCreateTime(new Date());
            this.baseMapper.insert(userInfo);
            UserInfo userInfo2 = this.baseMapper.selectOne(lambdaQueryWrapper);
            if(userInfo2 != null){
                String token = JwtHelper.createToken(Long.valueOf(userInfo2.getId()),
                        userInfo2.getWxName());
                addUserLog(request,userInfo2);
                LambdaQueryWrapper<Employee> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper2.eq(Employee::getPhone,userInfo2.getPhone());
                Employee employee = employeeMapper.selectOne(lambdaQueryWrapper2);
                if(employee != null){
                    res.put("employeeId",employee.getId());
                }

                res.put("UserData",userInfo2);
                res.put("token",token);
            }

        }
        return res;
    }



    @Override
    public Result selectAllGroupById(int pageNum,int limit) {

        //1.查询所有客户数
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        int count = Math.toIntExact(userInfoMapper.selectCount(wrapper));
        // 2.计算总页数（必须确定每页显示多少页 pagesize = limit）
        int pageCount =(count%limit == 0)? count/limit : count/limit+1;

        //3.查询当前页的数据（因为留言中需要回复信息，因此需要连表查询----自定义） 查看当前页的数据
        int start =(pageNum-1)*limit;

        List<EvEdApFvVo> evEdApFvVos = userInfoMapper.selectPartGroupById(start,limit);
        if (evEdApFvVos.size() == 0){
            return Result.success(ResultCodeEnum.FAIL.getCode(),ResultCodeEnum.FAIL.getMessage());
        }else {
            return Result.success(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMessage(),new PageHelper<EvEdApFvVo>(count,pageCount,evEdApFvVos));
        }
    }
    //通过 客户编号，或者微信名字，手机号查询EvEdApFvVo信息（都是唯一的）
    @Override
    public Result selectEvEdApFvVo(String condition,int pageNum,int limit) {
        //1.查询所有客户数
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        int count = Math.toIntExact(userInfoMapper.selectCount(wrapper));
        // 2.计算总页数（必须确定每页显示多少页 pagesize = limit）
        int pageCount =(count%limit == 0)? count/limit : count/limit+1;

        //3.查询当前页的数据（因为留言中需要回复信息，因此需要连表查询----自定义） 查看当前页的数据
        int start =(pageNum-1)*limit;
        List<EvEdApFvVo> evEdApFvVos = userInfoMapper.selectEvEdApFvVo(condition,start,limit);
        if (evEdApFvVos==null){
            return Result.success(ResultCodeEnum.FAIL.getCode(),ResultCodeEnum.FAIL.getMessage());
        }else {
            return Result.success(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMessage(),new PageHelper<EvEdApFvVo>(count,pageCount,evEdApFvVos));
        }
    }
}
